from microbit import *
from IoTbit import *

print("start iot")
iot: IOT
try:
    iot = IOT()
except Exception as e:
    uart.init(baudrate=115200)
    print(e)

def upload():
    global iot,count,connect
    display.scroll('uuuu')
    try:
        if iot.connectKidsiot("aeb6NOxsUJGmEjru","1"):
                display.scroll('TCPTCP')
                iot.uploadKidsiot("1")
                sleep(1000)
        else:
            uart.init(baudrate=115200)
            print('connect failed')
            print(iot.logger.getLatest())
    except Exception as e:
         uart.init(baudrate=115200)
         print(str(e))
         
    uart.init(baudrate=115200)
    print(iot.logger.getLatest())

count = 0
connect = False


def doConn():
    global iot,count,connect
    while True:
        count = count + 1
        display.scroll(str(count))
        sleep(1200)

        if iot.connectWIFI("oneplus7t","314314314"):
            connect = True
            display.scroll("SS22")
            uart.init(baudrate=115200)
            print(iot.logger.getLatest())
            sleep(500)
            uart.init(baudrate=115200, bits=8, parity=None, stop=1, tx=TX, rx=RX)
            break
        else:
            connect = False
            display.scroll("SS11")
            uart.init(baudrate=115200)
            print(iot.logger.getLatest())
            break
    

while True:
    if button_a.is_pressed():
        if connect:
            display.show(Image.HAPPY)
            sleep(1000)
            upload()
        else:
            display.show(Image.SAD)
            sleep(1000)
    elif button_b.is_pressed():
        if connect:
            display.show(Image.YES)
        else:
            display.show(Image.NO)
            sleep(500)
    elif pin_logo.is_touched():
         doConn()